package com.admin.logging.service.impl;

import cn.hutool.core.lang.Dict;
import com.admin.common.utils.PageResult;
import com.admin.common.utils.PageUtil;
import com.admin.logging.dto.SysLogQueryDTO;
import com.admin.logging.entity.SysLog;
import com.admin.logging.mapper.SysLogMapper;
import com.admin.logging.service.SysLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author sq-lan
 */
@Service
@RequiredArgsConstructor
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {


    @Override
    public PageResult<SysLog> paging(SysLogQueryDTO dto) {
        PageHelper.startPage(dto.getCurrent(), dto.getSize());
        List<SysLog> list = this.list(dto);
        return PageUtil.toPageHelper(list);
    }

    @Override
    public List<SysLog> list(SysLogQueryDTO dto) {
        LambdaQueryWrapper<SysLog> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(dto.getLogType() != null, SysLog::getLogType, dto.getLogType());
        wrapper.eq(dto.getOperateType() != null, SysLog::getOperateType, dto.getOperateType());
        wrapper.like(StringUtils.hasText(dto.getUsername()), SysLog::getUsername, dto.getUsername());
        wrapper.like(StringUtils.hasText(dto.getModule()), SysLog::getModule, dto.getModule());
        if (dto.getCreateTime() != null && !dto.getCreateTime().isEmpty()) {
            wrapper.between(SysLog::getCreateTime, dto.getCreateTime().get(0), dto.getCreateTime().get(1));
        }
        wrapper.select(SysLog::getId, SysLog::getUsername, SysLog::getModule,
                SysLog::getRequestIp, SysLog::getAddress, SysLog::getBrowser,
                SysLog::getLogType, SysLog::getMethod, SysLog::getOperateType,
                SysLog::getParams, SysLog::getCreateTime, SysLog::getTime);
        return this.list(wrapper);
    }

    @Override
    public void add(SysLog sysLog) {
        save(sysLog);
    }

    @Override
    public Object exceptionDetail(int id) {
        String details = this.getOne(Wrappers.<SysLog>lambdaQuery().eq(SysLog::getId, id).select(SysLog::getExceptionDetail)).getExceptionDetail();
        return Dict.create().set("exception", details);
    }


}
